<template>
  <div>
    <el-col class="account">
      <h3>账户设置</h3>
      <el-row class="setting">
        <el-col :span="12">
          <span class="setting-type">账号</span>
          <span class="setting-value">{{ filterPhone(phone) }}</span>
        </el-col>
        <el-col :span="12">
          <el-button @click="handleChangePhone">更改</el-button>
        </el-col>
      </el-row>
      <el-row class="setting">
        <el-col :span="12">
          <span class="setting-type">密码</span>
          <span class="setting-value">{{ pwdStatus ? ' 已设置，可通过账户密码登录' : '未设置密码' }}</span>
        </el-col>
        <el-col :span="12">
          <el-button @click="changePwd">更改</el-button>
        </el-col>
      </el-row>
      <el-row class="setting">
        <el-col :span="12">
          <span class="setting-type">所属单位</span>
          <div class="setting-value">
            单位名称：<span class="setting-value-unit">{{ unitInfo.unit_name }}</span> 单位代码：<span
              class="setting-value-unit"
              >{{ unitInfo.unit_code }}</span
            >
          </div>
        </el-col>
        <el-col :span="12">
          <el-button @click="changeUnit">更改</el-button>
        </el-col>
      </el-row>
    </el-col>
    <simpleDialog
      v-model="isShowDialog"
      :title="dialogConfig.title"
      @confirm="() => dialogConfig.onConfirm()"
      @cancel="onCancel()"
    >
      <div class="flex-col dialog dialog--phone" v-if="dialogConfig.type === 'phone'">
        <el-input v-model="newPhone" placeholder="请输入手机号" />
        <el-input v-model="varifyCode" placeholder="请输入验证码">
          <template #suffix>
            <span class="varify-code" v-show="codeFlag" @click="getVarifyMsg">获取验证码</span>
            <span v-show="!codeFlag">{{ `${time}秒后重新获取` }}</span>
          </template>
        </el-input>
      </div>
      <div class="flex-col dialog dialog--varify" v-if="dialogConfig.type === 'varify'">
        <div class="dialog--varify-origin">
          原手机号
          <span class="dialog--varify-origin-phone">{{ filterPhone(phone) }}</span>
        </div>
        <el-input v-model="msgCode" placeholder="请输入验证码">
          <template #suffix>
            <span class="varify-code" v-show="codeFlag" @click="getVarifyCode">获取验证码</span>
            <span v-show="!codeFlag">{{ `${time}秒后重新获取` }}</span>
          </template>
        </el-input>
      </div>
      <div class="flex-col dialog dialog--password" v-if="dialogConfig.type === 'password'">
        <el-input v-model="pwdCurrent" type="password" placeholder="请输入当前密码" />
        <el-input v-model="pwdNew" type="password" placeholder="请输入新密码" />
        <el-input v-model="pwdNewConfirm" type="password" placeholder="请确认新密码" />
      </div>
      <div class="flex-col dialog dialog--unit" v-if="dialogConfig.type === 'unit'">
        <div class="dialog--unit-old">
          单位名称
          <span class="dialog--unit-old-name" :title="unitInfo.unit_name">{{ unitInfo.unit_name }}</span>
        </div>
        <div class="dialog--unit-old">
          单位代码
          <span class="dialog--unit-old-name">{{ unitInfo.unit_code }}</span>
        </div>
        <el-select v-model="company" placeholder="请选择新的单位" class="unit-select" size="large">
          <el-option v-for="item in unitList" :key="item.id" :label="item.unit_name" :value="item.id" />
        </el-select>
      </div>
    </simpleDialog>
  </div>
</template>
<script lang="ts" setup>
import {ElMessage} from 'element-plus';
import {ref, reactive, onMounted} from 'vue';
import simpleDialog from '@/components/comSimpleDialog/comSimpleDialog.vue';
import registerApi from '@/api/register.ts';
import personalApi from '@/api/personalApi.ts';

const phone = ref('');
const pwdStatus = ref(true);
const unitInfo = ref({});
const codeFlag = ref(true);
const timer = ref(null);
const msgCode = ref('');
const time = ref(60);

const isShowDialog = ref(false);
type DialogCallback = Function;
// eslint-disable-next-line no-shadow
enum DialogType {
  password = 'password',
  unit = 'unit',
  varify = 'varify',
  mobile = 'phone',
}
interface DialogConfig {
  title: string;
  type: DialogType;
  onConfirm?: DialogCallback;
  onCancel?: DialogCallback;
}
const dialogConfig = reactive<DialogConfig>({
  title: '123',
  type: DialogType.mobile,
});
// 打开对话框
function showDialog(config: DialogConfig) {
  dialogConfig.title = config.title;
  dialogConfig.type = config.type;
  dialogConfig.onConfirm = config.onConfirm;
  isShowDialog.value = true;
}
// 关闭对话框
const onCancel = () => {
  msgCode.value = '';
  varifyCode.value = '';
  newPhone.value = '';
  varifyCode.value = '';
  pwdCurrent.value = '';
  pwdNew.value = '';
  pwdNewConfirm.value = '';
  company.value = '';
  isShowDialog.value = false;
};
// 修改手机号
const newPhone = ref();
const varifyCode = ref();
const handleChangePhone = () => {
  varify();
};
const changePhone = () => {
  const onVarify = () => {
    // 验证策略
    if (!varifyCode.value && !newPhone.value) {
      ElMessage.error('请输入手机号和验证码');
      return;
    }
    personalApi
      .updatePhone({
        mobile: newPhone.value,
        sms_code: varifyCode.value,
      })
      .then((res) => {
        if (res.status === 0) {
          isShowDialog.value = false;
          ElMessage.success(res.message);
          getUserInfo();
        }
      })
      .catch((err) => {
        throw err;
      });
  };
  showDialog({
    title: '更改手机号',
    type: DialogType.mobile,
    onConfirm: onVarify,
  });
};
// 身份验证
const varify = () => {
  // 身份验证回调
  const onVarify = () => {
    if (!msgCode.value) {
      ElMessage.warning('请输入验证码');
      return;
    }

    personalApi
      .verifyMobile({sms_code: msgCode.value})
      .then((res) => {
        if (res.status === 0) {
          varifyCode.value = '';
          isShowDialog.value = false;
          codeFlag.value = true;
          clearInterval(timer.value);
          timer.value = null;
          time.value = 0;
          changePhone();
        }
      })
      .catch((err) => {
        throw err;
      });
  };
  showDialog({
    title: '身份验证',
    type: DialogType.varify,
    onConfirm: onVarify,
  });
};

// 获取验证码
const getVarifyCode = () => {
  registerApi
    .getMsgCode({mobile: phone.value, action: 'verify_mobile'})
    .then((res) => {
      ElMessage.success(res.message);
      timeCountdown();
    })
    .catch((err) => {
      throw err;
    });
};
const getVarifyMsg = () => {
  registerApi
    .getMsgCode({mobile: newPhone.value, action: 'change_mobile'})
    .then((res) => {
      ElMessage.success(res.message);
      timeCountdown();
    })
    .catch((err) => {
      throw err;
    });
};

// 定时器
const timeCountdown = () => {
  const TIME_COUNT = 60;
  if (!timer.value) {
    time.value = TIME_COUNT;
    codeFlag.value = false;
    timer.value = setInterval(() => {
      if (time.value > 0 && time.value <= TIME_COUNT) {
        time.value--;
      } else {
        codeFlag.value = true;
        clearInterval(timer.value);
        timer.value = null;
      }
    }, 1000);
  }
};
// 点击密码
const pwdCurrent = ref('');
const pwdNew = ref('');
const pwdNewConfirm = ref('');
const changePwd = () => {
  // 修改密码回调
  const onVarify = () => {
    if (pwdNewConfirm.value !== pwdNew.value) {
      ElMessage.warning('两次输入的新密码不一致');
      return;
    }
    personalApi
      .updatePassword({
        old_password: pwdCurrent.value,
        new_password: pwdNew.value,
      })
      .then((res) => {
        if (res.status === 0) {
          ElMessage.success('修改密码成功');
          isShowDialog.value = false;
          getUserInfo();
        }
      })
      .catch((err) => {
        throw err;
      });
  };
  showDialog({
    title: '更改密码',
    type: DialogType.password,
    onConfirm: onVarify,
  });
};
// 点击修改单位
const unitList = ref([]);
const company = ref('');
const changeUnit = () => {
  getCompanyList();
  // 修改单位回调
  const onVarify = () => {
    if (!company.value) {
      ElMessage.warning('请选择单位');
    }
    personalApi
      .updateCompany({unit_id: company.value})
      .then((res) => {
        if (res.status === 0) {
          ElMessage.success(res.message);
          isShowDialog.value = false;
          getUserInfo();
        }
      })
      .catch((err) => {
        throw err;
      });
  };
  showDialog({
    title: '更改单位',
    type: DialogType.unit,
    onConfirm: onVarify,
  });
};
// 获取单位列表
const getCompanyList = () => {
  registerApi
    .getCompanyList()
    .then((res) => {
      unitList.value = res.data;
    })
    .catch((err) => {
      throw err;
    });
};
// 获取个人信息
const getUserInfo = () => {
  personalApi
    .getUserInfo()
    .then((res) => {
      if (res.status === 0) {
        unitInfo.value = res.data.user_unit;
        phone.value = res.data.mobile;
      }
    })
    .catch((err) => {
      throw err;
    });
};
onMounted(() => {
  getUserInfo();
});

const filterPhone = (telPhone: string): string => {
  const left = telPhone.substring(0, 3);
  const right = telPhone.substring(7);
  return `${left}****${right}`;
};
</script>
<style lang="scss" scoped>
span {
  cursor: default;
}
.account {
  width: 100%;
  padding: 30px;
  .setting {
    width: 100%;
    height: 97px;
    background: #ffffff;
    box-shadow: 4px 4px 4px 2px rgba(221, 229, 237, 0.5);
    padding: 20px 0 20px 30px;
    margin-bottom: 14px;
    .el-col:nth-child(1) {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
    }

    .el-col:nth-child(2) {
      display: flex;
      height: 100%;
      justify-content: flex-end;
      align-items: center;
      padding-right: 30px;
    }

    &-type {
      color: #3c4353;
      font-size: 14px;
      font-weight: bold;
      line-height: 1.8em;
    }
    &-value {
      color: #838a9d;
      font-size: 13px;

      &-unit {
        color: rgb(49, 120, 222);
        font-weight: bold;
        cursor: pointer;
        &:hover {
          color: rgba(49, 120, 222, 0.8);
        }
      }
    }
    .el-button {
      margin: 0;
      width: 98px;
      height: 36px;
      border-radius: 2px;
      border: 1px solid #1890ff;
      color: #1890ff;
      font-size: 14px;
    }
  }
}
.dialog {
  align-items: center;
  padding: 24px 40px 16px;
  .el-input {
    margin-bottom: 14px;
    height: 32px;
    box-sizing: border-box;
    :deep(.el-input__wrapper) {
      padding: 0 10px;
    }
  }
  .el-select {
    width: 100%;
    height: 32px;
    margin-bottom: 14px;
    :deep(.el-input__wrapper) {
      padding: 0 10px;
    }
    &:deep(.el-input__inner) {
      height: 32px;
    }
  }

  &--varify {
    &-origin {
      display: inline-block;
      align-self: flex-start;
      margin-bottom: 20px;
      &-phone {
        margin-left: 20px;
        font-weight: bold;
        color: #333333;
      }
    }
  }

  &--unit {
    &-old {
      align-self: flex-start;
      margin-bottom: 13px;
      width: 100%;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      &-name {
        margin-left: 15px;
        color: rgb(49, 120, 222);
        font-weight: bold;
      }
    }
    .unit-select {
      margin-top: 11px;
    }
  }
}

.varify-code {
  color: #1182fb;
  font-size: 13px;
  cursor: pointer;
  &:hover {
    opacity: 0.6;
  }
}
</style>
